(function () {
    function ResultController() {
        this.isGaming    = false;
        this.RoundID     = null;
        this.UserSeatID  = null;
        this.Stage       = null;
        this.SeatPanel   = null;
        this.UserID      = null;
        this.ResultUI    = null;
        this.AllShootUI  = null;
        this.SpecialUI   = null;
        this.WaitingUI   = null;
        this.isShowWait  = false;
        this.tableStatus = null;

        this._firstCards  = [];
        this._secondCards = [];
        this._thirdCards  = [];
        this._shoot       = [];
        this._allShoot    = [];
        this._special     = [];
        this._winAmount   = [];
        this._myResult    = {
            "sp" : null,
            "first" : null,
            "second" : null,
            "third" : null,
            "total" : 0,
            "total_real" : null
        };


        viewer.register("arena.start", this.start.bind(this));
        viewer.register("arena.resize", this.resize.bind(this));
        viewer.register("room.loaded", this.init.bind(this));
        viewer.register("room::leaveTable", this.leaveRoom.bind(this));
        viewer.register("room::into", this.roomInto.bind(this));
        viewer.register("game::started", this.gameStart.bind(this));
        viewer.register("game::over", this.settlement.bind(this));
        viewer.register("game::waiting", this.reset.bind(this));
        viewer.register("result.compare", this.compare.bind(this));
        viewer.register("result.shoot", this.compareShoot.bind(this));
        viewer.register("result.special", this.showSpeicalDialog.bind(this));
    }
    var _proto = ResultController.prototype;

    /**
     * @privite
     * 处理推送的结算结果
     * 
     * @param {Array} results 结算结果
     */
    _proto.formatData = function (results) {
        var SeatPanel   = this.SeatPanel;

        var firstCards  = this._firstCards;
        var secondCards = this._secondCards;
        var thirdCards  = this._thirdCards;
        var shoot       = this._shoot;
        var special     = this._special;
        var winAmount   = this._winAmount;
        var myResult    = this._myResult;

        for(var i in results){
            if(results[i].uid == 0){continue;};

            var result   = results[i];
            var position = result.position;
            var poker    = result.poker;

            var spFlag   = (result.sp? true : false);
            var seat     = SeatPanel.getChildByName("Seat." + position);

            utils.log("spFlag", spFlag);
            if(!spFlag){
                firstCards.push({
                    cards : poker[0].cardArr,
                    name  : poker[0].cardName,
                    type  : poker[0].cardType,
                    score : poker[0].score,
                    seat  : seat
                });

                secondCards.push({
                    cards : poker[1].cardArr,
                    name  : poker[1].cardName,
                    type  : poker[1].cardType,
                    score : poker[1].score,
                    seat  : seat
                });

                thirdCards.push({
                    cards : poker[2].cardArr,
                    name  : poker[2].cardName,
                    type  : poker[2].cardType,
                    score : poker[2].score,
                    seat  : seat
                });

                shoot.push({
                    seat       : seat,
                    shoot      : result.shoot,
                    allShoot   : result.allShoot,
                    totalScore : result.totalScore
                });

                if((result.allShoot | 0) === 1){
                    this._allShoot = result.poker[0].cardArr.concat(result.poker[1].cardArr.concat(result.poker[2].cardArr));
                }
            }else{
                special.push({
                    name  : result.sp.name,
                    type  : result.sp.type,
                    cards : result.poker[0].cardArr.concat(result.poker[1].cardArr.concat(result.poker[2].cardArr)),
                    seat  : seat
                });
            }

            winAmount.push({
                coin : result.amount,
                win  : result.win_amount,
                seat : seat,
            });

            if(result.uid === this.UserID){
                myResult.sp = spFlag;
                myResult.first = poker[0].score;
                myResult.second = poker[1].score;
                myResult.third = poker[2].score;
                myResult.total_real = result.totalScore;
            }
        }

        firstCards.sort(function (a, b) {return a.score - b.score});
        secondCards.sort(function (a, b) {return a.score - b.score});
        thirdCards.sort(function (a, b) {return a.score - b.score});
    }

    /**
     * @privite
     * 更新结算面板的数据
     * 
     * @param {String} line 当前行名字
     */
    _proto.changeResultPanel = function (line) {
        if(!this.isGaming){return;}
        var linePanel = this.ResultUI[line + "Panel"];
        var lineUI    = this.ResultUI[line];
        var totalPanel= this.ResultUI.totalPanel;
        var totalUI   = this.ResultUI.total;
        var myResult  = this._myResult;
        var lineScore = myResult[line];

        if(line){
            linePanel.visible = true;
            totalPanel.visible = true;

            if(lineScore >= 0){
                lineUI.font = "font_win";
                lineUI.text = "+" + lineScore;
            }else{
                lineUI.font = "font_lose";
                lineUI.text = lineScore;
            }

            //utils.log("first", myResult.total, lineScore);
            myResult.total += lineScore;
            if(myResult.total >= 0){
                totalUI.font = "font_win";
                totalUI.text = "+" + myResult.total;
            }else{
                totalUI.font = "font_lose";
                totalUI.text = myResult.total;
            }
        }else{
            if(myResult.total_real >= 0){
                totalUI.font = "font_win";
                totalUI.text = "+" + myResult.total_real;
            }else{
                totalUI.font = "font_lose";
                totalUI.text = myResult.total_real;
            }
        }
    }
    /**
     * @privite
     * 玩家开始比牌
     * 
     * @param {Object} lineData 当前行数据
     * @param {String} curLine  当前行名字
     * @param {String} nextLine 下一行名字
     */
    _proto.compareLine = function (lineData, curLine, nextLine){
        var size = lineData.length - 1;

        for(var i in lineData){
            (function (result, i, size, curLine, nextLine, resultCtrl) {

                setTimeout(function () {

                    if(i !== size){
                        result.seat.compare(curLine, result);
                    }else{
                        resultCtrl.changeResultPanel(curLine);

                        result.seat.compare(curLine, result, function () {
                            utils.log("compare." + curLine + " index:" + i + " animation completed");
                            
                            setTimeout(function () {
                                viewer.publish("result.compare", nextLine);
                            }, 1000);
                        });
                    }

                }, i * 1000);

            })(lineData[i], (i | 0), size, curLine, nextLine, this);
        }
    }

    _proto.compareShoot = function (index) {
        utils.log("compare.shoot--------->");

        var size      = this._shoot.length;
        var shoot     = this._shoot[index];
        var SeatPanel = this.SeatPanel;

        if(size === index){
            //viewer.publish("result.compare", "special");
            this.changeResultPanel();
            if(this._allShoot.length !== 0){
                this.AllShootUI.show(function () {
                    viewer.publish("result.compare", "special");
                });
            }else{
                viewer.publish("result.compare", "special");
            }
            return;
        }
        
        if(shoot.shoot.length != 0){
            var target = shoot.shoot;
            var seat = shoot.seat;
            var targetSize = target.length - 1;

            for(var i in target){

                var targetSeat = SeatPanel.getChildByName("Seat." + target[i]);

                (function (seat, target, i, size, index) {

                    setTimeout(function () {

                        if(i !== size){
                            seat.shoot(target);
                        }else{
                            seat.shoot(target, function () {
                                utils.log("compare.shoot index:" + i + " animation completed");
                                viewer.publish("result.shoot", index + 1);
                            });
                        }

                    }, i * 1000);

                })(seat, targetSeat, (i | 0), targetSize, index);
            }
        }else{
            viewer.publish("result.shoot", index + 1);
        }
    }

    _proto.showSpeicalDialog = function (index) {
        utils.log("compare.special--------->");

        var size = this._special.length;
        var specialData = this._special[index];
        
        if(size === index){
            viewer.publish("result.compare", "score");
            return;
        }else{
            this.SpecialUI.show(specialData, function () {
                utils.log("compare.special index:" + index + " dialog closed");
                viewer.publish("result.special", index + 1);
            });
        }
    }

    _proto.showFinalScore = function () {
        var winAmount = this._winAmount;
        var SeatPanel = this.SeatPanel;
        var _fromPos = [];
        var _toPos = [];
        var _winOrLose = null;

        if(this.ResultUI){
            this.ResultUI.visible = false;
        }
        
        if(this._myResult.total_real >= 0){
            _winOrLose = "win";
        }else{
            _winOrLose = "lose";
        }

        for(var i in winAmount){
            var seat = winAmount[i].seat;
            var win  = winAmount[i].win;

            seat.coin = winAmount[i].coin;
            seat.result(win);
            
            if(win >= 0){
                _toPos.push({
                    x : seat.x,
                    y : seat.y
                });
            }else{
                _fromPos.push({
                    x : seat.x,
                    y : seat.y
                });
            }
        }

        var _toSize = _toPos.length;
        var _fromSize = _fromPos.length;
        var _totalSize = _fromSize > _toSize ? _fromSize : _toSize;

        var _coinTotal = _totalSize * 5;
        var _coinSingle = _coinTotal / _fromSize;

        var _fromIndex = 0;
        var _toIndex =0;

        if(_toSize != 0 && _fromSize != 0){
            for(var i = 0; i < _totalSize; i ++){
                _fromIndex = i;
                _toIndex = i;

                if(_fromIndex >= _fromSize){
                    _fromIndex = _fromSize - 1;
                }
                if(_toIndex >= _toSize){
                    _toIndex = _toSize - 1;
                }


                for(var j = 0; j < 5; j ++){

                    var _coin = new Laya.Image("res/result/win_coin.png");

                    _coin.x = _fromPos[_fromIndex].x + 52;
                    _coin.y = _fromPos[_fromIndex].y + 52;

                    SeatPanel.addChild(_coin);
                        
                    Laya.Tween.to(_coin, {x : Math.random() * 80 + 335, y : Math.random() * 80 + 627}, 500, null, Laya.Handler.create(_coin, function (_to) {

                        Laya.Tween.to(this, {x : _to.x + 52, y : _to.y + 52}, 500, null, Laya.Handler.create(this, function () {
                            this.removeSelf();
                            _coin = null;
                        }), (120 - j * 30) + 400);

                    }, [_toPos[_toIndex]]), j * 30);

                }
            }
            Laya.SoundManager.playSound("sound/coin.mp3");

            setTimeout(function () {
                utils.log(_winOrLose);
                Laya.SoundManager.playSound("sound/" + _winOrLose + ".mp3");
            }, 1500);
        }else{
            utils.log(_winOrLose);
            Laya.SoundManager.playSound("sound/" + _winOrLose + ".mp3");
        }

        if(this.isGaming){
            setTimeout(function() {
                viewer.publish("io.emit", {
                    cmd : "game::reset",
                    params : {
                        token : token,
                        roundId : this.RoundID
                    }
                });
            }.bind(this), 3000);
        }
    }
    /**
     * @privite
     * 显示“等待下一局开始”文字动画
     */
    _proto.showWaiting = function () {
        if(Arena.CurScene !== "room"){return;}
        if(this.isShowWait){return;}

        this.WaitingUI.display();
    }
    _proto.showResultImmediately = function () {

    }

    /**
     * @public
     * 接收game::over消息，游戏中的玩家开始比牌
     *
     * @param {Object} res 游戏结算的数据
     */
    _proto.settlement = function (res) {
        if(Arena.CurScene !== "room"){return;}
        // if(!this.isGaming){
        //     return;
        // }
        
        var results  = res.results;
        this.RoundID = res.roundId;

        this.formatData(results);

        utils.log("firstCards");
        utils.log(this._firstCards);
        utils.log("secondCards");
        utils.log(this._secondCards);
        utils.log("thirdCards");
        utils.log(this._thirdCards);
        utils.log("shoot");
        utils.log(this._shoot);
        utils.log("allShoot");
        utils.log(this._allShoot);
        utils.log("special");
        utils.log(this._special);
        utils.log("winAmount");
        utils.log(this._winAmount);
        utils.log("myResult");
        utils.log(this._myResult);

        Laya.SoundManager.playSound("sound/compare.mp3");
        setTimeout(function () {
            viewer.publish("result.compare", "first");
        }, 1200);
        // this.compareFirst();
    }
    /**
     * @public
     * 接收result.compare消息，改变比牌流程
     *
     * @param {String} line 比牌当前流程
     */
    _proto.compare = function (line) {
        switch(line){
            case "first":
                if(this.isGaming){
                    var resultUI = new ui.Room.UI.ResultUI();

                    utils.log("compare.first");
                    utils.log(this._firstCards);

                    resultUI.x = (Laya.stage.width - 750) / 2 + 560;;
                    resultUI.y = 854;
                    this.Stage.addChildAt(resultUI, 1);
                    this.ResultUI = resultUI;
                }

                this.compareLine(this._firstCards, "first", "second");
                break;
            case "second":
                utils.log("compare.second");
                utils.log(this._secondCards);

                //this.changeResultPanel("first");
                this.compareLine(this._secondCards, "second", "third");
                break;
            case "third":
                utils.log("compare.third");
                utils.log(this._thirdCards);

                //this.changeResultPanel("second");
                this.compareLine(this._thirdCards, "third", "shoot");
                break;
            case "shoot":
                utils.log("result.process shoot");

                //this.changeResultPanel("third");
                viewer.publish("result.shoot", 0);
                break;
            case "special":
                utils.log("result.process special");

                viewer.publish("result.special", 0);
                break;
            case "score":
                utils.log("result.process showfinalscore");

                this.showFinalScore();
                break;
        }
    }
    /**
     * @public
     * 游戏开始时监听game::waiting消息，重置相关变量
     */
    _proto.reset = function () {
        this.Stage.removeChild(this.ResultUI);
        
        if(this.WaitingUI){
            this.WaitingUI.close();
        }

        this.isGaming   = false;
        this.RoundID    = null;
        this.ResultUI   = null;
        this.isShowWait = false;

        this._firstCards  = [];
        this._secondCards = [];
        this._thirdCards  = [];
        this._shoot       = [];
        this._allShoot    = [];
        this._special     = [];
        this._winAmount   = [];
        this._myResult    = {
            "sp" : null,
            "first" : null,
            "second" : null,
            "third" : null,
            "total" : 0,
            "total_real" : null
        };
    }
    _proto.gameStart = function (res) {
        if(Arena.CurScene !== "room"){return;}

        var positions = res.position;
        var UserSeatID = this.UserSeatID;

        utils.log(positions, UserSeatID);
        for(var i in positions){
            if(positions[i] == UserSeatID){
                this.isGaming = true;
                return;
            }
        }
    }
    _proto.roomInto = function (res) {
        if(Arena.CurScene !== "room"){return;}
        this.tableStatus = res.tableStatus | 0;
        var players    = res.list;
        var UserID     = this.UserID;
        this.SeatPanel = this.Stage.getChildByName("seat.panel");

        for(var i in players){
            var player = players[i];
            var status = player.gameStatus | 0;
            
            if(player.uid == UserID){
                this.UserSeatID = player.position;
                
                if(status === 3 || status === 4){
                    this.isGaming = true;
                }
            }
        }
        if(res.type == 1){
            utils.log("用户座位ID:" + this.UserSeatID)
        }else if(res.type == 2){
            this.reset();
        }

        if(this.tableStatus === 5){
            setTimeout(function(){
                this.showWaiting();
            }.bind(this), 0);
        }
    }
    /**
     * @public
     * 监听room::leaveRoom消息，初始化相关变量
     */
    _proto.leaveRoom = function () {
        this.reset();

        this.ResultUI   = null;
        this.AllShootUI = null;
        this.SpecialUI  = null;
        this.UserSeatID = null;
        this.WaitingUI  = null;
        this.tableStatus = null;
    }
    /**
     * @public
     * 监听room.loaded消息，初始化相关变量
     */
    _proto.init = function () {
        //this.ResultUI = new ui.Room.UI.ResultUI();
        setTimeout(function() {
            this.AllShootUI = new ui.Room.ResultAllShoot();
            this.SpecialUI  = new ui.Room.ResultSpecial();            
            this.WaitingUI  = new ui.Room.Waiting();
        }.bind(this), 0);
    }
    /**
     * @public
     * 游戏开始时监听arena.start消息，初始化相关变量
     */
    _proto.start = function () {
        this.Stage = Arena.Stage;
        this.UserID = Arena.UserID;
    }
    /**
     * @public
     * 监听arena.resize消息，重置界面位置
     */
    _proto.resize = function () {
        if(this.ResultUI){
            this.ResultUI.x = (Laya.stage.width - 750) / 2 + 560;
        }
        if(this.WaitingUI){
            this.WaitingUI.centerX = 0;
        }
    }

    new ResultController();
})();